package cn.sample.security.config;

import cn.sample.security.json.filter.JsonAuthenticationFilter;
import cn.sample.security.json.filter.JsonTokenAuthenticationFilter;
import cn.sample.security.json.handler.JsonAccessDeniedHandler;
import cn.sample.security.json.handler.JsonLogoutHandler;
import cn.sample.security.json.handler.JsonLogoutSuccessHandler;
import cn.sample.security.json.handler.JsonUnAuthenticationEntryPoint;
import cn.sample.security.manager.RequestAuthorizationManager;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * <h2></h2>
 *
 * <p>Security 配置类</p>
 *
 * @author HKD
 */
@EnableWebSecurity
public class SecurityConfig {

    @Resource
    private JsonAuthenticationFilter jsonAuthenticationFilter;
    @Resource
    private JsonUnAuthenticationEntryPoint jsonUnAuthenticationEntryPoint;
    @Resource
    private JsonTokenAuthenticationFilter jsonTokenAuthenticationFilter;
    @Resource
    private JsonLogoutHandler jsonLogoutHandler;
    @Resource
    private JsonLogoutSuccessHandler jsonLogoutSuccessHandler;

    @Resource
    private RequestAuthorizationManager requestAuthorizationManager;
    @Resource
    private JsonAccessDeniedHandler jsonAccessDeniedHandler;


    /**
     * 一个系统可以配置多个 SecurityFilterChain
     */
    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
        http.csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // json token 登录
        http.addFilterBefore(jsonTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        // json 登录
        http.addFilterBefore(jsonAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        http.authorizeHttpRequests()
                .antMatchers(HttpMethod.POST,"/login").permitAll()
                .anyRequest().access(requestAuthorizationManager);

        // 退出
        http.logout().logoutUrl("/logout")
                .addLogoutHandler(jsonLogoutHandler)
                .logoutSuccessHandler(jsonLogoutSuccessHandler);

        // 异常处理
        http.exceptionHandling()
                .authenticationEntryPoint(jsonUnAuthenticationEntryPoint)
                .accessDeniedHandler(jsonAccessDeniedHandler);

        return http.build();
    }



}
